package com.qding.park.manager.service.core.biz;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.adapter.AdapterException;
import com.qding.park.common.core.exceptions.business.manager.adapterfactory.AdapterProxyCreateFail;
import com.qding.park.common.core.exceptions.business.manager.service.ServiceCoreException;
import com.qding.park.common.utils.ListUtil;
import com.qding.park.common.utils.OrderNumUtil;
import com.qding.park.manager.adapter.factory.AdapterParkProxyFactory;
import com.qding.park.manager.cache.ConfigDataCacheInter;
import com.qding.park.manager.cache.UserCacheInter;
import com.qding.park.manager.pojo.TbCarlock;
import com.qding.park.manager.pojo.TbParkspace;
import com.qding.park.manager.pojo.TbUserInfo;
import com.qding.park.manager.pojo.TblockcarAlarm;
import com.qding.park.manager.pojo.ap.ApCarLockAlarm;
import com.qding.park.manager.pojo.enums.OrderServiceType;
import com.qding.park.manager.pojo.enums.RecordStatusEnum;
import com.qding.park.manager.pojo.enums.UserTypeEnum;
import com.qding.park.manager.pojo.sms.device.OutCheckAlarm;
import com.qding.park.manager.service.core.mapper.TbCarlockMapper;
import com.qding.park.manager.service.core.mapper.TbInoutRecordMapper;
import com.qding.park.manager.service.core.mapper.TbParkspaceMapper;
import com.qding.park.manager.service.core.mapper.TbUserInfoMapper;
import com.qding.park.manager.service.core.mapper.TblockcarAlarmMapper;
import com.qding.park.manager.sms.DevicePushInterfaceService;
import com.qding.park.manager.sms.SmsInterfaceServiec;
import com.qding.park.target.common.adapter.LockCarAdapter;
import com.qding.park.target.common.entity.AdLockCarOrder;

@Component("lockCarBiz")
public class LockCarBiz {

	private static final Log _log = LogFactory.getLog(LockCarBiz.class);

	@Autowired
	private AdapterParkProxyFactory adapterParkProxyFactory;

	@Autowired
	private TbCarlockMapper tbCarlockMapper;

	@Autowired
	private TbUserInfoMapper tbUserInfoMapper;

	@Autowired
	private TbParkspaceMapper tbParkspaceMapper;

	@Autowired
	private TbInoutRecordMapper tbInoutRecordMapper;

	@Autowired
	private TblockcarAlarmMapper tblockcarAlarmMapper;

	@Autowired
	private InoutcheckBiz inoutcheckBiz;

	@Autowired
	private DevicePushInterfaceService devicePushInterfaceService;
	
	@Autowired
	private SmsInterfaceServiec smsInterfaceServiec;

	@Autowired
	private ConfigDataCacheInter configDataCacheInter;
	
	@Autowired
	private UserCacheInter userCacheInter;

	@Transactional(rollbackFor = Throwable.class)
	public void alarmCockCar(ApCarLockAlarm apCarLockAlarm) {
		_log.info(apCarLockAlarm);
		// 报警时间
		Date alarmTime = apCarLockAlarm.getAlarmTime();
		// 卡号
		String cardCode = apCarLockAlarm.getCardCode();
		// 车牌
		String carNum = apCarLockAlarm.getCarNum();
		// 出场岗停
		String ourRoom = apCarLockAlarm.getOutRoom();
		// 停车场id
		String parkCode = apCarLockAlarm.getParkId();
		// 车场软件id
		String supplyId = apCarLockAlarm.getSupplyID();
		TbParkspace tbParkspace = configDataCacheInter.queryParkSpace(parkCode, Integer.valueOf(supplyId));
		int parkId = tbParkspace.getId();
		TbUserInfo tbUserInfo = tbCarlockMapper.queryLockUser(parkId, carNum);
		TblockcarAlarm tblockcarAlarm = new TblockcarAlarm();
		if(tbUserInfo==null){
			_log.error("没有找到锁车用户....不进行处理");
			return;
		}
		tblockcarAlarm.setCarNum(carNum);
		tblockcarAlarm.setParkID(parkId);
		tblockcarAlarm.setParkName(tbParkspace.getName());
		tblockcarAlarm.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
		tblockcarAlarm.setUserID(tbUserInfo.getId());
		int num = tblockcarAlarmMapper.save(tblockcarAlarm);
//		int userId=apCarLockAlarm.
		TbCarlock tbCarlock=tbCarlockMapper.queryByParkIdCarNum(parkId, carNum);
		if (num != 0&&tbCarlock!=null) {
			OutCheckAlarm alarm = new OutCheckAlarm();
			alarm.setCarNum(carNum);
			alarm.setMemberId(tbUserInfo.getBjCode());
			
			int userId=tbCarlock.getUserID();
			String tel=	userCacheInter.userId2tel(String.valueOf(userId));
			alarm.setMobile(tel);
			//将推送消息　改为发送短信
//			devicePushInterfaceService.outCheckAlarm(alarm);
			if(!StringUtils.isBlank(tel)){
				smsInterfaceServiec.lockcar_checkout_alarm(alarm);
			}
			
		}

	}

	@Transactional(rollbackFor = Throwable.class)
	public String createLockCarOrder(TbCarlock tbCarlock)
			throws AdapterProxyCreateFail, ServiceCoreException, AdapterException {

		/********* 判断车辆是否停在本车场 **********/
		int parkId = tbCarlock.getParkID();
		String carNum = tbCarlock.getCarNum();
		// int num=tbInoutRecordMapper.inByCarnumParkid(parkId,carNum);
		// if(num==0){
		// //车辆没有停在此车场
		// throw new
		// ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_CAR_NOTIN_PARK.getId(),
		// null,
		// ExceptionMessage.createExceptionMessage(
		// ServiceCoreException.TypeEnum.EXCEPTION_CAR_NOTIN_PARK.getDesc(),
		// "车辆没有停在此车场",
		// "车场=" + parkId + " 车牌=" + carNum));
		// }
		if (!inoutcheckBiz.isPresence(parkId, carNum)) {
			// 车辆没有停在此车场
			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_CAR_NOTIN_PARK.getId(), null,
					ExceptionMessage.createExceptionMessage(
							ServiceCoreException.TypeEnum.EXCEPTION_CAR_NOTIN_PARK.getDesc(), "车辆未进场，不支持锁车",
							"车场=" + parkId + " 车牌=" + carNum));
		}
		/********* 判断车辆是否停在本车场 **********/

		/******* 判断是否已经锁车了 如果已经锁车了就不允许锁车了 ****************/
		List<TbCarlock> lockList = tbCarlockMapper.lockedByParkidCarnum(parkId, carNum);
		if (!ListUtil.isEmpty(lockList)) {
			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_EXIST_CARLOCAK.getId(), null,
					ExceptionMessage.createExceptionMessage(
							ServiceCoreException.TypeEnum.EXCEPTION_EXIST_CARLOCAK.getDesc(), "此车辆已锁，请勿重复锁车",
							"车场=" + parkId + " 车牌=" + carNum));
		}

		/**********************/
		String bjuserid = tbCarlock.getBjuserid();

		// TbUserInfo tbUserInfo =
		// tbUserInfoMapper.queryUserByBjUserId(bjuserid);
		TbUserInfo tbUserInfo = tbUserInfoMapper.queryUseByBjuseridType(bjuserid, UserTypeEnum.REGISTER_USER.getType());
		tbCarlock.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
		tbCarlock.setUserID(tbUserInfo.getId());

		TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(tbCarlock.getParkID());
		tbCarlock.setParkName(tbParkspace.getName());
		tbCarlock.setId(OrderNumUtil.getOrderNum(tbUserInfo.getId(), OrderServiceType.CARLOCK.getTag()));
		int tag = tbCarlockMapper.save(tbCarlock);

		if (tag == 0) {
			// 如果没有保存成功 则说明此车辆已经被锁
			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_EXIST_CARLOCAK.getId(), null,
					ExceptionMessage.createExceptionMessage(
							ServiceCoreException.TypeEnum.EXCEPTION_EXIST_CARLOCAK.getDesc(), "此车辆已锁，请勿重复锁车",
							"车场=" + parkId + " 车牌=" + carNum));
		}
		String orderId = tbCarlock.getId();
		String parkCode = tbParkspace.getParkCode();

		/****** 下发锁车单 ***********/
		int supplierId = tbParkspace.getSupplierId();
		LockCarAdapter adapterProxy = adapterParkProxyFactory.getLockCarAdapter(String.valueOf(supplierId));
		AdLockCarOrder apLockCarOrder = new AdLockCarOrder();
		apLockCarOrder.setCarNum(carNum);
		apLockCarOrder.setOrderId(orderId);
		apLockCarOrder.setParkCode(parkCode);
		apLockCarOrder.setStartTime(tbCarlock.getStartTime());
		apLockCarOrder.setEndTime(tbCarlock.getEndTime());
		adapterProxy.createLockCarOrder(apLockCarOrder);
		/******* 下发锁车单 ***********/
		return tbCarlock.getId();
	}

	@Transactional(rollbackFor = Throwable.class)
	public void unLockCar(String orderId) throws AdapterProxyCreateFail, AdapterException, ServiceCoreException {
		// 更新锁车单状态
		int num = tbCarlockMapper.unLockCar(orderId, RecordStatusEnum.INVALID.getStatus());
		if (num == 0) {
			throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NOTFIND_CARLOCK.getId(), null,
					ExceptionMessage.createExceptionMessage(
							ServiceCoreException.TypeEnum.EXCEPTION_NOTFIND_CARLOCK.getDesc(), "此锁轩单锁车失效",
							"orderId=" + orderId));
		}
		TbCarlock tbCarlock = tbCarlockMapper.queryById(orderId);
		TbParkspace tbParkspace = configDataCacheInter.queryParkSpace(tbCarlock.getParkID());
		
		/****** 下发解锁车单 ***********/
		int supplierId = tbParkspace.getSupplierId();
		String parkCode = tbParkspace.getParkCode();
		String carNum = tbCarlock.getCarNum();
		LockCarAdapter adapterProxy = adapterParkProxyFactory.getLockCarAdapter(String.valueOf(supplierId));
		AdLockCarOrder apLockCarOrder = new AdLockCarOrder();
		apLockCarOrder.setCarNum(carNum);
		apLockCarOrder.setOrderId(String.valueOf(orderId));
		apLockCarOrder.setParkCode(parkCode);
		apLockCarOrder.setStartTime(tbCarlock.getStartTime());
		apLockCarOrder.setEndTime(tbCarlock.getEndTime());
		adapterProxy.unLockCar(apLockCarOrder);
		/******* 下发解锁车单 ***********/
		
	}

	// public int saveAlarmLockCar(TblockcarAlarm tblockcarAlarm) {
	//
	// return tblockcarAlarmMapper.save(tblockcarAlarm);
	// }

//	@Transactional(rollbackFor = Throwable.class)
//	public void lockTimeOut(TbCarlock carlock) throws AdapterProxyCreateFail, AdapterException {
//		String id = carlock.getId();
//		TbCarlock tbCarlock = tbCarlockMapper.queryById(id);
//		tbCarlock.setStatus(CarLockStatusEnum.OVERTIME_STATUS.getStatus());
//		int num = tbCarlockMapper.lockTimeOut(tbCarlock);
//
//		if (num == 0) {
//			_log.info("id:" + id + " 没有此状态数据");
////			return;
//		}
//
//		/****** 向车场下发解锁车单 ***************/
//		TbParkspace tbParkspace = tbParkspaceMapper.queryParkInfoByParkId(tbCarlock.getParkID());
//		int supplierId = tbParkspace.getSupplierId();
//		String parkCode = tbParkspace.getParkCode();
//		String carNum = tbCarlock.getCarNum();
//		AdapterProxy adapterProxy = adapterParkProxyFactory.createAdapterParkProxyBySupplierId(supplierId);
//		AdLockCarOrder apLockCarOrder = new AdLockCarOrder();
//		apLockCarOrder.setCarNum(carNum);
//		apLockCarOrder.setOrderId(String.valueOf(id));
//		apLockCarOrder.setParkCode(parkCode);
//		apLockCarOrder.setStartTime(tbCarlock.getStartTime());
//		apLockCarOrder.setEndTime(tbCarlock.getEndTime());
//		adapterProxy.getLockCarAdapter().unLockCar(apLockCarOrder);
//		/****** 向车场下发解锁车单 ***************/
//
//	}
}
